package com.koomii.myproject.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.lang.StringUtils;

import com.koomii.common.util.TextUtils;
import com.koomii.common.util.security.BASE64Kit;

/**
 * @author J.L
 *此类为一些关键的数据 做 遮掩。
 */
public class HideUtils {

	private static final int BASIC = 1;

	private static final char[] PLACEHOLDER = { 'X', 'K', 'Y', 'a', 'i', 'c',
			'd' };

	private static final int MARK = 0xee;

//	private static final char JOIN_SIGN = '@';

	/**
	 * 使用精确到天的数字 和 参数 进行 操作，生成一段掩盖字符
	 * 
	 * @param core
	 * @return
	 */
	public static String coverByDay(int core) {
		int temp = (core * BASIC) ^ createMask();
		Random r = new Random();
		StringBuilder sb = new StringBuilder();
		while (temp > 10 || temp % 10 != 0) {
			sb.append((char) ((temp % 10) + 65));
			if (r.nextInt(11) % 3 == 0) {
				sb.append(PLACEHOLDER[r.nextInt(PLACEHOLDER.length)]);
			}
			temp = temp / 10;
		}
		return sb.toString();
	}

	private static int createMask() {
		Date today = new Date();
		return Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(today));
	}

	/**
	 * 反掩盖 coverByDay(int core)方法
	 * 
	 * @param str
	 * @return
	 */
	public static int discoverByDay(String str) {
		if (StringUtils.isEmpty(str))
			return 0;
		str = deletePlaceholder(str);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			int temp = (int) (str.charAt(i) - 65);
			sb.append(temp > 0 ? temp : temp * -1);
		}
		String result = sb.reverse().toString();
		for (int i = 0; i < result.length(); i++) {
			if (!Character.isDigit(result.charAt(i))) {
				return 0;
			}
		}
		long temp = result.length() > 19 ? 0 : Long.parseLong(result);
		if (temp > Integer.MAX_VALUE) {
			return 0;
		}
		int buf = (int) temp;
		return (buf ^ createMask()) / BASIC;
	}

	/**
	 * 仅 iso-8859-1 有效 遮盖 字符
	 * 
	 * @param str
	 * @return
	 */
	public static String coverString(String str) {
		byte[] bytes = new byte[str.length()];
		for (int i = 0; i < str.length(); i++) {
			int a = (int) str.charAt(i);
			bytes[i] = (byte) ~((a ^ MARK) & 0xff);
		}
		BASE64Kit kit = new BASE64Kit();
		return kit.encode(bytes);
	}

	/**
	 * 仅 iso-8859-1 有效 反遮盖字符
	 * 
	 * @param str
	 * @return
	 */
	public static String discoverString(String str) {
		if (TextUtils.isEmpty(str))
			return "";
		BASE64Kit kit = new BASE64Kit();
		byte[] bytes = kit.decode(str);
		for (int i = 0; i < bytes.length; i++) {
			byte a = bytes[i];
			bytes[i] = (byte) (((~a) ^ MARK) & 0xff);
		}
		return new String(bytes);
	}

	private static String deletePlaceholder(String str) {
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<str.length();i++){
			char c = str.charAt(i);
			boolean notHave = true;
			for(int j=0;j<PLACEHOLDER.length;j++){
				if(PLACEHOLDER[j]==c){
					notHave=false;
					break;
				}
			}
			if(notHave){
				sb.append(c);
			}
		}
		return sb.toString();
	}
}
